memchr関数は、メモリ領域から1文字検索します。
#include <string.h>
void *memchr(const void *s, int c, size_t n);
*sは検索対象のメモリ領域の先頭アドレスを指定します。
cは検索する文字(検索キー1文字)を指定します。
nは検索範囲をバイト単位で指定します。(*sからnバイトが検索範囲になります。)
戻り値として、検索文字が見つかった場合は、その文字のポインタを、見つからなかった場合はNULLを返します。
プログラム 例
#include <stdio.h>
#include <string.h>
#define SIZE 1024
int main()
{
FILE *fp;
char path[50]; /* 入力ファイルのパス名 */
char buff[SIZE];
char *start_ptr; /* 検索開始位置 */
char *end_ptr; /* 検索終了位置 */
char *search_ptr; /* 検索結果文字位置 */
int moji; /* 検索文字 */
int search_cnt; /* 検索結果文字数 */
int return_code = 0;
printf('検索するファイルのパス名を入力してください ==> ');
scanf('%s%*c', path);
if ((fp = fopen(path, 'r')) != NULL) {
printf('検索する文字を入力してください ==> ');
scanf('%c', &moji);
search_cnt = 0;
while(fgets(buff, SIZE, fp) != NULL) {
start_ptr = buff;
end_ptr = buff + strlen(buff);
do {
/* 文字の検索 */
if((search_ptr =
memchr(start_ptr, moji, strlen(start_ptr))) != NULL) {
++search_cnt;
start_ptr = search_ptr + 1;
}
else {
start_ptr = end_ptr;
}
} while (start_ptr < end_ptr);
}
fclose(fp);
printf('%cは%d個ありました\n', moji, search_cnt);
}
else {
printf('%sのオープンに失敗しました\n', path);
return_code = 1;
}
return return_code;
}
例の実行結果
$ cat temp.txt
#include <stdio.h>
int main()
{
printf('Hello World!!.\n');
return 0;
}
$
$ ./memchr.exe
検索するファイルのパス名を入力してください ==> temp.txt
検索する文字を入力してください ==> ;
;は2個ありました
$